package com.gitee.zycra.union.api.service;

import com.gitee.zycra.union.api.common.bo.CommonResult;
import com.gitee.zycra.union.api.common.model.ApiUserGroup;
import com.gitee.zycra.union.api.common.vo.UserInfoVO;
import com.gitee.zycra.union.api.manager.ApiUserGroupManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author zycra
 */
@Slf4j
@Service
public class ApiUserGroupService {

    @Autowired
    private ApiUserGroupManager apiUserGroupManager;

    /**
     * 添加用户到项目组
     *
     * @param groupId 项目组ID
     * @param userId  用户ID
     * @param auth    权限
     * @return 添加结果
     */
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> addUser(Long groupId, Long userId, Integer auth) {
        apiUserGroupManager.updateToDelete(groupId, userId);
        apiUserGroupManager.insertApiUserGroup(new ApiUserGroup().setGroupId(groupId).setUserId(userId).setAuth(auth));
        return CommonResult.success();
    }

    /**
     * 修改用户权限
     *
     * @param groupId 项目组ID
     * @param userId  用户ID
     * @param auth    权限
     * @return 修改结果
     */
    public CommonResult<String> changeUserAuth(Long groupId, Long userId, Integer auth) {
        apiUserGroupManager.updateAuth(groupId, userId, auth);
        return CommonResult.success();
    }

    /**
     * 移除项目组内用户
     *
     * @param groupId 项目组ID
     * @param userId  用户ID
     * @return 修改结果
     */
    public CommonResult<String> removeUser(Long groupId, Long userId) {
        apiUserGroupManager.removeUser(groupId, userId);
        return CommonResult.success();
    }

    /**
     * 根据用户ID和组ID查询权限
     *
     * @param userId  用户ID
     * @param groupId 组ID
     * @return 权限
     */
    public String selectAuthByUserIdAndGroupId(Long userId, Long groupId) {
        return apiUserGroupManager.selectAuthByUserIdAndGroupId(userId, groupId);
    }

    /**
     * 根据项目组ID查询其他组非超级管理员用户
     *
     * @param groupId 项目组ID
     * @return 用户列表
     */
    public CommonResult<List<UserInfoVO>> selectUserInfoForAddGroup(Long groupId) {
        return CommonResult.success(apiUserGroupManager.selectUserInfoForAddGroup(groupId));
    }
}
